package com.studentManagement.servlet;

import com.studentManagement.daoImpl.ClassDaoImpl;
import com.studentManagement.daoImpl.StudentDaoImpl;
import com.studentManagement.po.Student;
import com.studentManagement.service.ClassService;
import com.studentManagement.serviceImpl.ClassServiceImpl;
import com.studentManagement.serviceImpl.StudentServiceImpl;
import com.studentManagement.utils.Md5Util;
import net.sf.json.JSONArray;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Administrator on 2017/5/9 0009.
 */
@WebServlet(name = "StudentServlet")
public class StudentServlet extends HttpServlet {
    ClassService classService = new ClassServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String action = request.getParameter("action");
        if (action.equals("modifyStudentDetail")) {
            modifyStudentDetail(request, response);//学生详细信息修改（普通表单和文件）
        } else if (action.equals("keyPressTip")) {
            keyPressTip(request, response);//关键字搜索的提示信息
        } else if (action.equals("submitKeywords_pageNum_onePage")) {
            submitKeywords_pageNum_onePage(request, response);//提交关键字_页数_每页显示条数，进行查询
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");

        if (action.equals("getStudentDetail")) {
            //得到学生详细信息(student_id)
            getStudentDetail(request, response);
        } else if (action.equals("delStudent")) {
            //删除学生(student_id)
            delStudent(request, response);
        } else if (action.equals("addStudent")) {
            //添加学生(Student)
            addStudent(request, response);
        } else if (action.equals("student_idCanUsed")) {
           //判断学号是否可以使用（student_id)
            student_idCanUsed(request, response);
        } else if (action.equals("exportExcel")) {
            //数据导出excel
            exportExcel(request, response);
        } else if(action.equals("getDormitory_id")){
            getDormitory_id(request,response);
        }
    }

    private void getDormitory_id(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
        PrintWriter out = response.getWriter();
        String class_id = (String) request.getSession().getAttribute("class_id");
        List<String> list = classService.getDormitory_id(class_id);
        response.setContentType("text/xml;charset=UTF-8");
        out.print("<dormitory_id_message>");
        for (int i = 0; i < list.size(); i++) {
            out.print("<dormitory_id>" + list.get(i) + "</dormitory_id>");
        }
        out.print("</dormitory_id_message>");
    }
    private void modifyStudentDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Student student = new Student();
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            try {
                DiskFileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setHeaderEncoding("utf-8");
                upload.setSizeMax(10 * 1024 * 1024);

                List<FileItem> formItems = upload.parseRequest(request);
                Iterator<FileItem> iter = formItems.iterator();
                //依次处理每个表单域
                while (iter.hasNext()) {
                    FileItem item = iter.next();
                    //处理普通表单
                    if (item.isFormField()) {
                        if ("student_id".equals(item.getFieldName())) {
                            student.setStudent_id(item.getString("utf-8"));
                        }
                        if ("student_name".equals(item.getFieldName())) {
                            student.setStudent_name(item.getString("utf-8"));
                        }
                        if ("student_key".equals(item.getFieldName())) {
                            student.setStudent_key(item.getString("utf-8"));
                        }
                        if ("student_sex".equals(item.getFieldName())) {
                            student.setStudent_sex(item.getString("utf-8"));
                        }
                        if ("student_age".equals(item.getFieldName())) {
                            student.setStudent_age(Integer.parseInt(item.getString("utf-8")));
                        }
                        if ("student_state".equals(item.getFieldName())) {
                            student.setStudent_state(Integer.parseInt(item.getString("utf-8")));
                        }
                        if ("student_credit".equals(item.getFieldName())) {
                            student.setStudent_credit(Double.parseDouble(item.getString("utf-8")));
                        }
                        if ("student_phone".equals(item.getFieldName())) {
                            student.setStudent_phone(item.getString("utf-8"));
                        }
                        if ("student_address".equals(item.getFieldName())) {
                            student.setStudent_address(item.getString("utf-8"));
                        }
                        if ("student_qq".equals(item.getFieldName())) {
                            student.setStudent_qq(item.getString("utf-8"));
                        }
                        if ("student_nation".equals(item.getFieldName())) {
                            student.setStudent_nation(item.getString("utf-8"));
                        }
                        if ("student_dormitory_id".equals(item.getFieldName())) {
                            student.setStudent_dormitory_id(item.getString("utf-8"));
                        }
                        if ("student_class_id".equals(item.getFieldName())) {
                            student.setStudent_class_id(item.getString("utf-8"));
                        }
                        if ("student_duty".equals(item.getFieldName())) {
                            student.setStudent_duty(item.getString("utf-8"));
                        }
                        if ("student_enter_year".equals(item.getFieldName())) {
                            student.setStudent_enter_year(item.getString("utf-8"));
                        }
                        //处理文件表单
                    } else {
                        //获得文件名及路径
                        String fileName = item.getName();
                        String suffix = fileName.substring(fileName.indexOf(".") + 1).toLowerCase();
                        //图片格式判断
                        if (fileName != null && fileName.indexOf(".") != -1) {
                            if (suffix.equals("jpeg") || suffix.equals("jpg") || suffix.equals("gif") || suffix.equals("png") || suffix.equals("bmp") || suffix.equals("tiff")) {

                                String name = System.currentTimeMillis() + "." + fileName.substring(fileName.indexOf(".") + 1);
                                //如果目录不存在，则创建
                                File catalog = new File(getServletContext().getRealPath("/resources/images/upload"));
                                if (!catalog.exists()) {
                                    catalog.mkdirs();
                                }

                                File fullFile = new File(catalog, name);
                                student.setStudent_image_Path(name);
                                item.write(fullFile);
                                new ClassServiceImpl().updateStudentDetail(student);
                                request.setAttribute("message", "提交成功");
                            } else {
                                request.setAttribute("message", "请上传 jpeg/jpg/gif/png/bmp/tiff 格式的图片");
                                request.getServletContext().getRequestDispatcher(request.getContextPath() + "/jsp/teacher/right/class/studentDetail.jsp").forward(request, response);
                            }
                        } else {
                            student.setStudent_image_Path(classService.getStudentImg(student.getStudent_id()));
                            new ClassServiceImpl().updateStudentDetail(student);
                            request.setAttribute("message", "提交成功");
                        }
                        item.delete();
                    }
                }
            } catch (Exception e) {
                request.setAttribute("message", "错误信息: " + e.getMessage());
            }

            // 跳转到 studentDetail.jsp
            request.setAttribute("student", student);
            request.getServletContext().getRequestDispatcher(request.getContextPath() + "/jsp/teacher/class/studentDetail.jsp").forward(request, response);
        }
    }

    private void keyPressTip(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String keyWords = request.getParameter("keywords");
        List<String> list = new StudentServiceImpl().getTips_10(keyWords);
        JSONArray jsonArray = JSONArray.fromObject(list);
        out.print(jsonArray);
    }

    private void exportExcel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String class_id = (String) request.getSession().getAttribute("class_id");
        String exported = request.getParameter("exported");
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet(class_id);
        sheet.setDefaultColumnWidth(15);
        // 产生表格标题行
        String[] header = {"学号", "姓名", "性别", "状态", "学分", "手机号", "详细地址", "QQ", "民族", "宿舍", "班级", "班级职位", "入学年份"};
        HSSFRow headerRow = sheet.createRow(0);
        for (int i = 0; i < header.length; i++) {
            HSSFCell cell = headerRow.createCell(i);
            cell.setCellValue(header[i]);
        }
        //把内容写入excel
        List<Student> allStudent = new ArrayList<>();
        String excelName = null;
        if (exported.equals("studentList")) {
            allStudent = new ClassDaoImpl().queryAllStudentDetail(class_id);
            excelName = "班级信息表";
        } else if (exported.equals("studentLeader")) {
            allStudent = new StudentDaoImpl().queryStudentLeaderDetail(class_id);
            excelName = "班干信息表";
        }

        int index = 0;
        String state = "";
        for (int i = 0; i < allStudent.size(); i++) {
            if (allStudent.get(i).getStudent_state() == 1) {
                state = "在读";
            } else if (allStudent.get(i).getStudent_state() == 1) {
                state = "休学";
            } else if (allStudent.get(i).getStudent_state() == 1) {
                state = "退学";
            } else if (allStudent.get(i).getStudent_state() == 1) {
                state = "毕业";
            }
            HSSFRow row = sheet.createRow(++index);
            String[] bodyRow = {allStudent.get(i).getStudent_id(),
                allStudent.get(i).getStudent_name(), allStudent.get(i).getStudent_sex(), state,
                String.valueOf(allStudent.get(i).getStudent_credit()), allStudent.get(i).getStudent_phone(), allStudent.get(i).getStudent_address(),
                allStudent.get(i).getStudent_qq(), allStudent.get(i).getStudent_nation(), allStudent.get(i).getStudent_dormitory_id(),
                allStudent.get(i).getStudent_class_id(), allStudent.get(i).getStudent_duty(), allStudent.get(i).getStudent_enter_year()};
            for (int j = 0; j < bodyRow.length; j++) {
                HSSFCell cell = row.createCell(j);
                cell.setCellValue(bodyRow[j]);
            }
        }
        //下载提示框 设置response参数，可以打开下载页面
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            workbook.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String((class_id + excelName + ".xls").getBytes(), "iso-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
        }
    }

    private void submitKeywords_pageNum_onePage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String keywords = request.getParameter("keywords");
        int pageNum = Integer.parseInt(request.getParameter("pageNum"));
        int onePage = Integer.parseInt(request.getParameter("onePage"));
        List<Student> list = new StudentDaoImpl().getStudentDetail_byKeywords(keywords, pageNum, onePage);
        PrintWriter out = response.getWriter();
        JSONArray jsonArray = JSONArray.fromObject(list);
        out.print(jsonArray);
    }

    private void student_idCanUsed(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String student_id = request.getParameter("student_id");
        response.setContentType("text/xml;charset=UTF-8");
        if (classService.student_idCanUsed(student_id)) {
            out.print("<message>该学号可以使用</message>");
        } else {
            out.print("<message>该学号已被注册</message>");
        }
    }

    private void getStudentDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String student_id = request.getParameter("student_id");
        Student student = classService.getStudentDeTail(student_id);
        request.getSession().setAttribute("student", student);
        response.sendRedirect(request.getContextPath() + "/jsp/teacher/class/studentDetail.jsp");
    }

    private void delStudent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String student_id = request.getParameter("student_id");
        boolean result = classService.delStudent(student_id);
        response.setContentType("text/xml;charset=UTF-8");
        out.print("<message>");
        if (result) {
            out.print("删除成功");
        } else {
            out.print("删除失败");
        }
        out.print("</message>");
    }

    private void addStudent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String class_id = (String) request.getSession().getAttribute("class_id");
        Student student = new Student();
        //从前端获取的数据
        student.setStudent_id(request.getParameter("student_id"));
        student.setStudent_name(request.getParameter("student_name"));
        student.setStudent_sex(request.getParameter("student_sex"));
        student.setStudent_age(Integer.parseInt(request.getParameter("student_age")));
        student.setStudent_state(Integer.parseInt(request.getParameter("student_state")));
        student.setStudent_phone(request.getParameter("student_phone"));
        student.setStudent_qq(request.getParameter("student_qq"));
        student.setStudent_address(request.getParameter("student_address"));
        student.setStudent_nation(request.getParameter("student_nation"));
        student.setStudent_dormitory_id(request.getParameter("student_dormitory_id"));
        //自定义的数据
        student.setStudent_key(Md5Util.md5(request.getParameter("student_id")));
        student.setStudent_credit(0);
        student.setStudent_class_id(class_id);
        student.setStudent_duty("班级成员");
        student.setStudent_image_Path("");
        boolean boo = true;
        try {
            classService.addStudent(student);
        } catch (Exception e) {
            boo = false;
        }
        response.setContentType("text/xml;charset=UTF-8");
        if (boo) {
            out.print("<alert_message>添加成功</alert_message>");
        } else {
            out.print("<alert_message>添加失败</alert_message>");
        }
    }

}
